const express = require("express");
const router = express.Router();
const jwt = require('jsonwebtoken');
const config = require('../config'); // 配置文件
const mysqlUtil = require('../utils/mysqlUtil');

const { loginValidationRules } = require('../verify/login'); // 数据验证
const validate = require('../verify/checkValidationResult');

router.post("/login", loginValidationRules, validate, async (req, res) => {

    const { username, password } = req.body;

    // 验证用户名和密码
    const user = await mysqlUtil.query(`SELECT * FROM users WHERE username = '${username}' AND password = '${password}'`);
    console.log(user);
    //返回结果小于1就是用户名或密码错误
    if (user.length != 1) {
        return res.cc("用户名或密码错误");
    }


    try {
        // 生成 JWT 字符串
        const token = jwt.sign({ user: user[0] }, config.jwtSecretKey, {
            expiresIn: "2h",
        });

        res.send({
            status: true,
            msg: "登录成功",
            token,
        });
    } catch (error) {
        res.status(500).cc(error);
    }
});

// 退出登录
router.post("/logout", async (req, res) => {
    res.cc("退出成功", true);
})
module.exports = router;